from django.shortcuts import render

# Create your views here.
# users/views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .models import McUser, McGender
from .serializers import McUserSerializer
from app.common.pagination import StandardResultsSetPagination
import requests
import jwt
import datetime
from django.conf import settings
from Crypto.Cipher import AES
import base64
import json


# 查询所有用户
@api_view(["GET"])
def user_list(request):
    items = McUser.objects.all().order_by("-created_time")

    # 分页
    paginator = StandardResultsSetPagination()
    result_page = paginator.paginate_queryset(items, request)
    serializer = McUserSerializer(result_page, many=True)

    return paginator.get_paginated_response(serializer.data)


# 查询单个用户
@api_view(["GET"])
def user_detail(request, pk):
    try:
        user = McUser.objects.get(pk=pk)
    except McUser.DoesNotExist:
        return Response({"error": "User not found"}, status=status.HTTP_404_NOT_FOUND)

    serializer = McUserSerializer(user)
    return Response(serializer.data)


# 新增用户
@api_view(["POST"])
def user_create(request):
    serializer = McUserSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 更新用户
@api_view(["PUT"])
def user_update(request, pk):
    try:
        user = McUser.objects.get(pk=pk)
    except McUser.DoesNotExist:
        return Response({"error": "User not found"}, status=status.HTTP_404_NOT_FOUND)

    serializer = McUserSerializer(user, data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 删除用户
@api_view(["DELETE"])
def user_delete(request, pk):
    try:
        user = McUser.objects.get(pk=pk)
    except McUser.DoesNotExist:
        return Response({"error": "User not found"}, status=status.HTTP_404_NOT_FOUND)

    user.delete()
    return Response(status=status.HTTP_204_NO_CONTENT)


def decrypt_user_data(session_key, encrypted_data, iv):
    session_key = base64.b64decode(session_key)
    encrypted_data = base64.b64decode(encrypted_data)
    iv = base64.b64decode(iv)

    cipher = AES.new(session_key, AES.MODE_CBC, iv)
    decrypted = cipher.decrypt(encrypted_data)

    # 去除填充
    pad = decrypted[-1]
    decrypted = decrypted[:-pad]
    return json.loads(decrypted.decode("utf-8"))


# 解密手机号
def decrypt_user_phone(encryptedData, session_key, iv):
    session_key_bytes = base64.b64decode(session_key)
    encrypted_bytes = base64.b64decode(encryptedData)
    iv_bytes = base64.b64decode(iv)
    cipher = AES.new(session_key_bytes, AES.MODE_CBC, iv_bytes)
    decrypted = cipher.decrypt(encrypted_bytes)
    decrypted = decrypted[: -decrypted[-1]]  # 去掉填充
    return json.loads(decrypted)


@api_view(["POST"])
def wechat_login(request):
    code = request.data.get("code")
    encryptedData = request.data.get("encryptedData")
    iv = request.data.get("iv")
    if not code:
        return Response({"error": "code is required"}, status=400)

    # 微信登录接口
    url = "https://api.weixin.qq.com/sns/jscode2session"
    params = {
        "appid": settings.WX_APPID,
        "secret": settings.WX_SECRET,
        "js_code": code,
        "grant_type": "authorization_code",
    }

    resp = requests.get(url, params=params)
    data = resp.json()

    if "errcode" in data:
        return Response({"error": data}, status=400)

    openid = data.get("openid")
    session_key = data.get("session_key")

    # 3. 生成 JWT Token
    payload = {
        "openid": openid,
        "exp": datetime.datetime.utcnow() + datetime.timedelta(days=7),
    }
    token = jwt.encode(payload, settings.JWT_SECRET_KEY, algorithm="HS256")
    user_info = decrypt_user_data(session_key, encryptedData, iv)

    # gender = McGender.objects.filter(name=).first()

    user = McUser.objects.get(open_id=openid)

    if not code:
        user = McUser.objects.create(
            open_id=openid,
            nick_name=user_info.get("nickName"),
            real_name=user_info.get("nickName"),
            gender_id=1,
            avatar=user_info.get("avatarUrl"),
        )
        user.save()
    serializer = McUserSerializer(user)
    return Response(
        {
            "user": serializer.data,
            "token": token,
        },
        status=status.HTTP_200_OK,
    )


@api_view(["POST"])
def phone_login(request):
    # 获取检查接口参数
    code = request.data.get("code")
    encryptedData = request.data.get("encryptedData")
    iv = request.data.get("iv")
    if not code or not encryptedData or not iv:
        return Response({"error": "参数缺失"}, status=400)

    # 获取 session_key
    appid = settings.WX_APPID
    secret = settings.WX_SECRET
    url = f"https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code"
    data = requests.get(url).json()

    session_key = data.get("session_key")
    openid = data.get("openid")

    if not session_key or not openid:
        return Response({"error": "微信接口返回错误"}, status=400)

    # 获取手机号信息
    phone_info = decrypt_user_phone(encryptedData, session_key, iv)
    phone_number = phone_info.get("phoneNumber")

    # 生成 JWT Token
    payload = {
        "openid": openid,
        "exp": datetime.datetime.utcnow() + datetime.timedelta(hours=2),
    }
    # token = jwt.encode(payload, "your-secret-key", algorithm="HS256")
    token = jwt.encode(payload, settings.JWT_SECRET_KEY, algorithm="HS256")
    # 解析保存用户信息
    user_info = decrypt_user_data(session_key, encryptedData, iv)

    print("login++++++++++++++++++++++>", openid)
    user, created = McUser.objects.get_or_create(
        open_id=openid,
        defaults={
            "phone": phone_number,
            "nick_name": user_info.get("nickName"),
            "real_name": user_info.get("nickName"),
            "gender_id": 1,
            "avatar": user_info.get("avatarUrl"),
        },
    )

    if not created:
        # 用户已存在，更新手机号、头像、昵称等信息
        user.phone = phone_number
        user.nick_name = user_info.get("nickName")
        user.real_name = user_info.get("nickName")
        user.avatar = user_info.get("avatarUrl")
        user.save()

    # user = McUser.objects.get(open_id=openid)

    # # TODO:性别未写入
    # if not code:
    #     user = McUser.objects.create(
    #         open_id=openid,
    #         phone=18200001111,
    #         nick_name=user_info.get("nickName"),
    #         real_name=user_info.get("nickName"),
    #         gender_id=1,
    #         avatar=user_info.get("avatarUrl"),
    #     )
    #     user.save()
    serializer = McUserSerializer(user)

    return Response(
        {
            "user": serializer.data,
            "token": token,
        }
    )


@api_view(["POST"])
def phone_login2(request):

    user = McUser.objects.create(
        open_id="zzzzzz",
        phone=18200001111,
        nick_name="zzzzzz",
        real_name="zzzzzz",
        gender_id=1,
        avatar="zzzzzz",
    )
    user.save()
    serializer = McUserSerializer(user)

    return Response(
        {
            "user": serializer.data,
        }
    )
